<template>
  <div class="login-container">
    <div class="nav">
      <van-icon name="home-o" @click="toIndex" />
      <van-nav-bar title="网易严选" />
      <van-icon name="search" />
    </div>

    <!-- logo -->
    <div class="logo">
      <img
        style="width: 200px"
        src="//yanxuan.nosdn.127.net/static-union/164793255107785e.png"
        alt=""
      />
    </div>

    <!-- 登录 -->
    <van-form @submit="onConfirm">
      <van-cell-group inset>
        <van-field
          v-model="phone"
          name="phone"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />

        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />

        <van-row>
          <van-col span="16">
            <van-field
              v-model="code"
              name="code"
              label="验证码"
              placeholder="验证码"
              :rules="[{ required: true, message: '请输入验证码' }]"
          /></van-col>
          <van-col span="8"
            ><van-button round type="success" @click="getCode">获取验证码</van-button></van-col
          >
        </van-row>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button block type="danger" native-type="submit"> 注册 </van-button>
      </div>
    </van-form>

    <!--  -->
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { reqCode, reqRegister } from '@/api/login'
import { showFailToast, showToast } from 'vant'
import 'vant/es/toast/style'

// 获取路由实例
const router = useRouter()

// 用户名
const phone = ref('')
// 和密码
const password = ref('')
// 验证码
const code = ref('')

// 点击获取验证码
const getCode = async () => {
  if (phone.value) {
    const res = await reqCode(phone.value)
    // 给code赋值
    code.value = res.data as string
  }
}

// 点击注册
const onConfirm = async (data: any) => {
  try {
    const res = await reqRegister(data)
    if (res) {
      // 跳转登录页
      router.push('/login')

      //  注册成功之后提示用户
      showToast('注册成功')

      // 清空验证码
      code.value = ''
    }
  } catch (error) {
    showFailToast('账号已被注册，请重新注册')

    // 清空验证码
    code.value = ''
  }
}

// 点击home回首页
const toIndex = () => {
  router.push('/')
}
</script>

<script lang="ts">
export default {
  name: 'VRegister'
}
</script>

<style lang="scss" scoped>
.logo {
  width: 400px;
  display: flex;
  justify-content: center;
  margin-top: 70px;
}
.nav {
  display: flex;
  justify-content: space-between;
  .van-icon {
    padding: 15px;
  }
  .van-nav-bar {
    width: 200px;
  }
}
</style>
